﻿using System;
using System.Collections.Generic;
using System.Web;
using System.Configuration;
using System.Xml;
using System.IO;

namespace AutoUpdater
{
    public class UpdateInfoSection : ConfigurationSection
    {
        public Dictionary<string, UpdateInfo> UpdateFiles = new Dictionary<string, UpdateInfo>(StringComparer.OrdinalIgnoreCase);

        protected override void DeserializeSection(XmlReader reader)
        {
            DeserializeSection(reader, AppDomain.CurrentDomain.BaseDirectory);
        }

        protected virtual void DeserializeSection(XmlReader reader, string folder)
        {
            while (reader.Read())
            {
                if (reader.NodeType == XmlNodeType.Element)
                {
                    switch (reader.Name)
                    {
                        case "File":
                            string fileName = reader.GetAttribute("FileName");
                            string versionType = reader.GetAttribute("VersionType");
                            string version = reader.GetAttribute("Version");
                            string isStartUp = reader.GetAttribute("IsStartUp");
                            string path = reader.GetAttribute("Path");
                            if (String.IsNullOrEmpty(path)) path = Path.Combine(folder, fileName);

                            UpdateFiles.Add(fileName, new UpdateInfo(
                                fileName,
                                String.IsNullOrEmpty(versionType) ? VersionType.FileVersion : (VersionType)Enum.Parse(typeof(VersionType), versionType, true),
                                version,
                                path,
                                String.IsNullOrEmpty(isStartUp) ? false : Boolean.Parse(isStartUp)));
                            break;
                        case "Folder":
                            DeserializeSection(reader, Path.Combine(folder, reader.GetAttribute("Path")));
                            break;
                    }
                }
                else if (reader.NodeType == XmlNodeType.EndElement) return;
            }
        }
    }

}